﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using AcadPos.Entity;
using AcadPosApp.Utilidades;
using System.Data;
using Microsoft.Reporting.WebForms;
using System.Globalization;

namespace AcadPosApp.ControlarMatricula
{
    public partial class HistoricoAluno : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                if (Session["idMatriculaSituacao"] != null)
                {
                    carregaDisciplinasMatricula();
                    pnlMatriculaDisciplinaPendente.Visible = true;
                    carregaDisciplinasMatriculaPendentes();

                }
                else
                    Response.Redirect("MatriculaAluno.aspx");
            }

            if (gvwDisciplinasAluno.SelectedIndex > -1)
            {
                pnlAcoesBotoes.Visible = true;
            }
            else
                pnlAcoesBotoes.Visible = false;
        }

        private void carregaDisciplinasMatricula()
        {
            MatriculaSessao matriculaSessao = (MatriculaSessao)Session["matriculaSessao"];
            Matricula matricula = new Matricula();
            matricula.IdMatricula = matriculaSessao.IdMatricula;
            gvwDisciplinasAluno.DataSource = ControlClass.CNMatricula.listaDisciplinasMatriculadasPorAluno(matricula);
            gvwDisciplinasAluno.DataBind();
        }

        private void carregaDisciplinasMatriculaPendentes()
        {
            MatriculaSessao matriculaSessao = (MatriculaSessao)Session["matriculaSessao"];
            Matricula matricula = new Matricula();
            matricula.IdMatricula = matriculaSessao.IdMatricula;
            gvwDisciplinasAlunoPendentes.DataSource = ControlClass.CNMatricula.listaDisciplinasMatriculadasPorAlunoPendentes(matricula);
            gvwDisciplinasAlunoPendentes.DataBind();
        }

        protected void gvwDisciplinasAluno_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            gvwDisciplinasAluno.PageIndex = e.NewPageIndex;
            carregaDisciplinasMatricula();
        }

        protected void gvwDisciplinasAluno_SelectedIndexChanged(object sender, EventArgs e)
        {
            pnlAcoesBotoes.Visible = true;
        }

        protected void btnJustificaFaltas_Click(object sender, EventArgs e)
        {
            if (gvwDisciplinasAluno.SelectedIndex > -1 && gvwDisciplinasAluno.Rows[gvwDisciplinasAluno.SelectedIndex].Cells[6].Text.ToString() == "RF")
            {
                pnlJustificaFaltas.Visible = true;
                lblDisciplina.Text = gvwDisciplinasAluno.Rows[gvwDisciplinasAluno.SelectedIndex].Cells[1].Text.ToString();
                txtJustificativa.Text = string.Empty;
                btnConfirmarJustFalta.CommandName = "Inserir";
            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", string.Format("alert('{0}');", Alertas.obterMsg((int)EnumAcadPos.Mensagem.Nada, "Selecione uma Disciplina que foi reprovada por Falta!")), true);
            }
        }

        protected void btnCancelarJustFalta_Click(object sender, EventArgs e)
        {
            pnlJustificaFaltas.Visible = false;
        }

        protected void btnConfirmarJustFalta_Click(object sender, EventArgs e)
        {
            try
            {
                if (gvwDisciplinasAluno.SelectedIndex > -1 && gvwDisciplinasAluno.Rows[gvwDisciplinasAluno.SelectedIndex].Cells[6].Text.ToString() == "RF")
                {
                    Matricula matricula = new Matricula();
                    matricula.IdMatriculaDisciplina = Convert.ToInt32(gvwDisciplinasAluno.DataKeys[gvwDisciplinasAluno.SelectedIndex]["ID_MATRICULA_DISCIPLINA"].ToString());
                    matricula.JustificativaFalta = txtJustificativa.Text;
                    if (btnConfirmarJustFalta.CommandName == "Inserir")
                    {
                        if (ControlClass.CNMatricula.insereJustificativaFalta(matricula))
                        {
                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", string.Format("alert('{0}');", Alertas.obterMsg((int)EnumAcadPos.Mensagem.SucessoInserir, "")), true);
                            pnlJustificaFaltas.Visible = false;
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", string.Format("alert('{0}');", Alertas.obterMsg((int)EnumAcadPos.Mensagem.Nada, "Erro na operação. Por favor, tente novamente.")), true);
                        }
                    }
                }
                else
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", string.Format("alert('{0}');", Alertas.obterMsg((int)EnumAcadPos.Mensagem.Nada, "Selecione uma Disciplina que foi reprovada por Falta!")), true);
                }
            }
            catch (Exception ex)
            {

                if (ex.Message.Contains("IX_TB_JUSTIFICATIVA"))
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", string.Format("alert('{0}');", Alertas.obterMsg((int)EnumAcadPos.Mensagem.Nada, "Já foi inserida uma justificativa para essa disciplina!")), true);
                else
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", string.Format("alert('{0}');", Alertas.obterMsg((int)EnumAcadPos.Mensagem.Erro, ex.Message.ToString())), true);
            }
        }

        protected void btnVoltarMatricula_Click(object sender, EventArgs e)
        {
            MatriculaSessao matriculaSessao = (MatriculaSessao)Session["matriculaSessao"];
            //matriculaSessao.Acao = "Excluir";
            Session["matriculaSessao"] = matriculaSessao;
            Session.Remove("idMatriculaSituacao");
            Session["saidaPagina"] = "FC";
            Response.Redirect("MatriculaAluno.aspx");
        }

        private void carregaEstadosCadastro()
        {
            ddlCadEstado.DataSource = ControlClass.CNEstado.listaTodosEstados();
            ddlCadEstado.DataTextField = "ESTADO";
            ddlCadEstado.DataValueField = "ID_ESTADO";
            ddlCadEstado.DataBind();
        }

        private void carregaPoloCadastro()
        {
            Polo polo = new Polo();
            polo.IdEstado = Convert.ToInt32(ddlCadEstado.SelectedValue);
            DataTable dt = ControlClass.CNPolo.listaPolosEstado(polo);
            ddlCadPolo.DataSource = dt;
            ddlCadPolo.DataTextField = "DESCRICAO";
            ddlCadPolo.DataValueField = "ID_POLO";
            ddlCadPolo.DataBind();
            ddlCadPolo.Items.Insert(0, new ListItem("Selecione", ""));
            if (dt.Rows.Count > 0)
            {
                ddlCadPolo.Enabled = true;
            }
            else
            {
                ddlCadPolo.Enabled = false;
                ddlCadPolo.Items.Clear();
            }
        }

        protected void btnMatriculaDisciplina_Click(object sender, EventArgs e)
        {
            pnlDisciplinasOfertadas.Visible = true;
            pnlMatriculaDisciplinaPendente.Visible = true;
            carregaEstadosCadastro();
            pnlHistorico.Enabled = false;
            ddlCadPolo.Items.Clear();
            ddlCadPolo.Enabled = false;
            gvwDisciplinasOfertadas.Visible = false;
            lblDisciplinaPendente.Text = gvwDisciplinasAluno.Rows[gvwDisciplinasAluno.SelectedIndex].Cells[1].Text.ToString();
            carregaDisciplinasMatriculaPendentes();
        }

        protected void ddlCadEstado_SelectedIndexChanged(object sender, EventArgs e)
        {
            carregaPoloCadastro();
            gvwDisciplinasOfertadas.Visible = false;
        }

        protected void ddlCadPolo_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (ddlCadPolo.SelectedValue != "")
            {
                gvwDisciplinasOfertadas.Visible = true;
                Disciplina disc = new Disciplina();
                disc.IdDisciplina = Convert.ToInt32(gvwDisciplinasAluno.DataKeys[gvwDisciplinasAluno.SelectedIndex]["ID_DISCIPLINA"].ToString());
                int idPolo = Convert.ToInt32(ddlCadPolo.SelectedValue);
                MatriculaSessao matricula = (MatriculaSessao)Session["matriculaSessao"];
                //MatriculaSessao matricula = new MatriculaSessao();
                int matriculaAluno = matricula.MatriculaAluno;
                gvwDisciplinasOfertadas.DataSource = ControlClass.CNMatricula.listaDiscMatriculaPendente(disc, idPolo, matriculaAluno);
                gvwDisciplinasOfertadas.DataBind();
                gvwDisciplinasOfertadas.SelectedIndex = -1;
            }
            else
            {
                gvwDisciplinasOfertadas.Visible = false;
            }

        }

        protected void btnCancelarMatriculaPendente_Click(object sender, EventArgs e)
        {
            pnlDisciplinasOfertadas.Visible = false;
            pnlMatriculaDisciplinaPendente.Visible = false;
            pnlHistorico.Enabled = true;
        }

        protected void btnConfirmarMatriculaPendente_Click(object sender, EventArgs e)
        {
            try
            {
                if (gvwDisciplinasOfertadas.SelectedIndex > -1 && gvwDisciplinasAluno.SelectedIndex > -1 && gvwDisciplinasAluno.Rows[gvwDisciplinasAluno.SelectedIndex].Cells[6].Text.ToString() == "RF")
                {
                    Financeiro financeiro = new Financeiro();
                    financeiro.IdMatriculaDisciplina = Convert.ToInt32(gvwDisciplinasAluno.DataKeys[gvwDisciplinasAluno.SelectedIndex]["ID_MATRICULA_DISCIPLINA"].ToString());
                    financeiro.IdTurma = Convert.ToInt32(gvwDisciplinasOfertadas.DataKeys[gvwDisciplinasOfertadas.SelectedIndex]["ID_TURMA"].ToString());
                    financeiro.IdMatrizCurricular = Convert.ToInt32(gvwDisciplinasOfertadas.DataKeys[gvwDisciplinasOfertadas.SelectedIndex]["ID_MATRIZ_CURRICULAR"].ToString());
                    financeiro.IdDisciplina = Convert.ToInt32(gvwDisciplinasOfertadas.DataKeys[gvwDisciplinasOfertadas.SelectedIndex]["ID_DISCIPLINA"].ToString());
                    financeiro.Termo = "";
                    financeiro.Parcela = 1;
                    financeiro.DataVencimento = DateTime.Now;
                                        
                    if (ControlClass.CNMatricula.insere1FinanceiroPendencia(financeiro))
                    {
                        gvwDisciplinasOfertadas.Visible = false;
                        ddlCadPolo.SelectedValue = "";
                        carregaDisciplinasMatriculaPendentes();
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", string.Format("alert('{0}');", Alertas.obterMsg((int)EnumAcadPos.Mensagem.SucessoInserir, "")), true);
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", string.Format("alert('{0}');", Alertas.obterMsg((int)EnumAcadPos.Mensagem.Nada, "Erro na operação. Por favor, tente novamente.")), true);
                    }

                }
                else
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", string.Format("alert('{0}');", Alertas.obterMsg((int)EnumAcadPos.Mensagem.Nada, "Selecione uma Disciplina para matricular!")), true);
                }
            }
            catch (Exception ex)
            {

                if (ex.Message.Contains("IX_TB_FINANCEIRO_PENDENCIA"))
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", string.Format("alert('{0}');", Alertas.obterMsg((int)EnumAcadPos.Mensagem.Nada, "Já foi inserida essa disciplina pendente para essa matrícula/ano/turma!")), true);
                else
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", string.Format("alert('{0}');", Alertas.obterMsg((int)EnumAcadPos.Mensagem.Nada, ex.Message.ToString())), true);
            }
        }

        protected void btnHistorico_Click(object sender, EventArgs e)
        {
            try
            {
                MatriculaSessao matriculaSessao = (MatriculaSessao)Session["matriculaSessao"];
                Matricula matricula = new Matricula();
                matricula.MatriculaAluno = matriculaSessao.MatriculaAluno;
                matricula.IdTurma = matriculaSessao.IdTurma;
                matricula.IdMatricula = matriculaSessao.IdMatricula;
                DataTable dtImp = ControlClass.CNMatricula.relatorioHistorico(matricula);

                if (dtImp.Rows.Count == 0)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", "bootbox.alert('Não há registros à serem impressos!', function() {});", true);
                }
                else
                {
                    ReportViewer ReportViewer1 = new ReportViewer();
                    ReportViewer1.Reset();
                    ReportViewer1.ProcessingMode = ProcessingMode.Local;
                    ReportViewer1.LocalReport.ReportPath = Server.MapPath(@"~/Relatorios/relHistorico.rdlc");
                    ReportViewer1.LocalReport.DataSources.Clear();

                    ReportParameter rp_aluno = new ReportParameter("rp_aluno", Server.HtmlDecode(matriculaSessao.MatriculaAluno.ToString() + " - " + matriculaSessao.NomeAlunoCompleto.ToString()));
                    ReportParameter rp_curso = new ReportParameter("rp_curso", Server.HtmlDecode(matriculaSessao.NomeCurso.ToString()));
                    ReportParameter rp_turma = new ReportParameter("rp_turma", Server.HtmlDecode(matriculaSessao.Turma.ToString()));
                    ReportParameter rp_modulo = new ReportParameter("rp_modulo", Server.HtmlDecode(matriculaSessao.NomeModulo.ToString()));
                    ReportParameter rp_curriculo = new ReportParameter("rp_curriculo", Server.HtmlDecode(matriculaSessao.Curriculo.ToString()));

                    ReportParameter[] ReportParans = new ReportParameter[] { rp_aluno, rp_curso, rp_turma, rp_curriculo, rp_modulo };

                    ReportViewer1.LocalReport.SetParameters(ReportParans);

                    ReportDataSource rds1 = new ReportDataSource();
                    rds1.Name = "DataSet1";
                    rds1.Value = dtImp;

                    ReportDataSource rds2 = new ReportDataSource();
                    rds2.Name = "DataSet2";
                    rds2.Value = ControlClass.CNParametros.getCabecalhoRelatorio();

                    ReportViewer1.LocalReport.DataSources.Clear();
                    ReportViewer1.LocalReport.DataSources.Add(rds1);
                    ReportViewer1.LocalReport.DataSources.Add(rds2);
                    ReportViewer1.LocalReport.Refresh();

                    #region Gerar PDF
                    Warning[] warn = null;
                    string[] streamids = null;
                    string mimeType = "application/pdf";
                    string encoding = string.Empty;
                    string extension = string.Empty;
                    byte[] byteViewer;

                    byteViewer = ReportViewer1.LocalReport.Render("pdf", null, out mimeType, out encoding, out extension, out streamids, out warn);
                    Response.Buffer = true;
                    Response.Clear();
                    Response.ContentType = "application/pdf";
                    Response.AddHeader("content-disposition", "attachment; filename=Historico.pdf");
                    Response.BinaryWrite(byteViewer);
                    Response.Flush();

                    Response.End();
                    Response.ClearContent();
                    #endregion
                }
            }
            catch (Exception)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", "bootbox.alert('Falha ao tentar gerar o relatório. Tente novamente!', function() {});", true);
            }
        }

        protected void gvwDisciplinasAlunoPendentes_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            int index = int.Parse((String)e.CommandArgument);
            if (e.CommandName == "RelCompMatricula")
            {
                geraComprovanteMatricula(index);
            }
            else if (e.CommandName == "boleto")
            {
                string pNossoNumero = gvwDisciplinasAlunoPendentes.DataKeys[index]["NOSSO_NUMERO"].ToString();
                DataTable dtDadosFinanceiro = ControlClass.CNMatricula.getFichaFinanceiraPendencia(pNossoNumero);
                if (dtDadosFinanceiro.Rows.Count > 0)
                {
                    Session["dadosParcelas"] = dtDadosFinanceiro;
                    Session["tipoBoleto"] = "PAGAMENTO PARCELAS";
                    MatriculaSessao matriculaSessao = (MatriculaSessao)Session["matriculaSessao"];
                    Session["InformacoesBoleto"] = Server.HtmlDecode("Curso: " + matriculaSessao.NomeCurso + "\nMódulo: " + matriculaSessao.NomeModulo + "\nDisciplina Pendência: " + gvwDisciplinasAlunoPendentes.Rows[index].Cells[0].Text);
                    ScriptManager.RegisterStartupScript(Page, typeof(Page), "OpenWindow", "window.open('../Boletos/boletoBanese.aspx', '_blank');", true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", "bootbox.alert('Não foram localizadas parcelas à serem pagas!', function() {});", true);
                }
            }
        }

        private void geraComprovanteMatricula(int index)
        {
            try
            {
                MatriculaSessao matriculaSessao = (MatriculaSessao)Session["matriculaSessao"];

                ReportViewer ReportViewer1 = new ReportViewer();
                ReportViewer1.Reset();
                ReportViewer1.ProcessingMode = ProcessingMode.Local;
                ReportViewer1.LocalReport.ReportPath = Server.MapPath(@"~/Relatorios/relComprovanteMatriculaDep.rdlc");
                ReportViewer1.LocalReport.DataSources.Clear();



                //Mês em português por extenso
                string mesExtenso = new DateTime(1900, DateTime.Now.Month, 1).ToString("MMMM", new CultureInfo("pt-BR"));
                string cpf = matriculaSessao.Cpf;
                string cpfformatado = Convert.ToUInt64(cpf).ToString(@"000\.000\.000\-00");

                ReportParameter rp_aluno = new ReportParameter("rp_aluno", Server.HtmlDecode(matriculaSessao.MatriculaAluno.ToString() + " - " + matriculaSessao.NomeAlunoCompleto.ToString()));
                ReportParameter rp_curso = new ReportParameter("rp_curso", Server.HtmlDecode(matriculaSessao.NomeCurso.ToString()));
                ReportParameter rp_turma = new ReportParameter("rp_turma", Server.HtmlDecode(matriculaSessao.Turma.ToString()));
                ReportParameter rp_modulo = new ReportParameter("rp_modulo", Server.HtmlDecode(matriculaSessao.NomeModulo.ToString()));
                ReportParameter rp_curriculo = new ReportParameter("rp_curriculo", Server.HtmlDecode(matriculaSessao.Curriculo.ToString()));
                ReportParameter rp_mes = new ReportParameter("rp_mes", Server.HtmlDecode(mesExtenso));
                ReportParameter rp_cpf = new ReportParameter("rp_cpf", Server.HtmlDecode(cpfformatado));
                ReportParameter rp_disciplina = new ReportParameter("rp_disciplina", Server.HtmlDecode(gvwDisciplinasAlunoPendentes.Rows[index].Cells[0].Text.ToString()));
                ReportParameter rp_cargaHoraria = new ReportParameter("rp_cargaHoraria", Server.HtmlDecode(gvwDisciplinasAlunoPendentes.Rows[index].Cells[1].Text.ToString()));
                ReportParameter[] ReportParans = new ReportParameter[] { rp_aluno, rp_curso, rp_turma, rp_curriculo, rp_modulo, rp_mes, rp_cpf, rp_disciplina, rp_cargaHoraria };

                ReportViewer1.LocalReport.SetParameters(ReportParans);



                ReportDataSource rds2 = new ReportDataSource();
                rds2.Name = "DataSet2";
                rds2.Value = ControlClass.CNParametros.getCabecalhoRelatorio();

                ReportViewer1.LocalReport.DataSources.Clear();
                ReportViewer1.LocalReport.DataSources.Add(rds2);
                ReportViewer1.LocalReport.Refresh();

                #region Gerar PDF
                Warning[] warn = null;
                string[] streamids = null;
                string mimeType = "application/pdf";
                string encoding = string.Empty;
                string extension = string.Empty;
                byte[] byteViewer;

                byteViewer = ReportViewer1.LocalReport.Render("pdf", null, out mimeType, out encoding, out extension, out streamids, out warn);
                Response.Buffer = true;
                Response.Clear();
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment; filename=CompMatricula.pdf");
                Response.BinaryWrite(byteViewer);
                Response.Flush();

                Response.End();
                Response.ClearContent();
                #endregion

            }
            catch (Exception)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Alert", "bootbox.alert('Falha ao tentar gerar o relatório. Tente novamente!', function() {});", true);
            }
        }

        protected void gvwDisciplinasAlunoPendentes_RowCreated(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                ImageButton button1 = (ImageButton)e.Row.FindControl("imgBoleto");
                button1.CommandArgument = e.Row.RowIndex.ToString();

                ImageButton button3 = (ImageButton)e.Row.FindControl("CompMatricula");
                button3.CommandArgument = e.Row.RowIndex.ToString();
            }
        }

        protected void gvwDisciplinasAlunoPendentes_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //if (e.Row.RowType == DataControlRowType.DataRow)
            //{
            //    if (e.Row.Cells[5].Text.ToString() != "EM ABERTA")
            //    {
            //        e.Row.Cells[8].Enabled = false;
            //    }
            //}
        }

        protected void gvwDisciplinasAluno_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.Header)
            {
                e.Row.Cells[8].Visible = false;
            }
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                if (e.Row.Cells[8].Text != "&nbsp;" && e.Row.Cells[8].Text != "")
                {
                    dataBound(sender, e);
                    e.Row.ToolTip = "Justif.: " + Server.HtmlDecode(e.Row.Cells[8].Text.ToString());
                    System.Web.UI.WebControls.Image imagem = ((System.Web.UI.WebControls.Image)e.Row.Cells[9].FindControl("Image1"));
                    imagem.Visible = true;
                }
                else
                {
                    System.Web.UI.WebControls.Image imagem = ((System.Web.UI.WebControls.Image)e.Row.Cells[9].FindControl("Image1"));
                    imagem.Visible = false;
                    e.Row.Cells[9].Text = "N/A";
                }
                e.Row.Cells[8].Visible = false;
            }
        }

        public void dataBound(object sender, GridViewRowEventArgs e)
        {
            System.Web.UI.WebControls.Image imagem = ((System.Web.UI.WebControls.Image)e.Row.Cells[9].FindControl("Image1"));
            string justificativa = Server.HtmlDecode(e.Row.Cells[8].Text.ToString());

            string javascript = string.Format("abreJanela();preencheObs({0}, {1})", "'" + justificativa + "'", lblJustificativa.ClientID);

            imagem.Attributes.Add("onclick", javascript);
        }



        protected void gvwDisciplinasAluno_SelectedIndexChanging(object sender, GridViewSelectEventArgs e)
        {

        }
    }
}